package view.zjitc.net.androidhomeworkview2;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

/**
 * @author 朱志文
 * @data 2019/10/10 0010
 */
@SuppressLint("AppCompatCustomView")
public class CustomView extends TextView {
    private float downY;
    private float downX;

    public CustomView(Context context) {
        super(context);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getRawX();
        float y = event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = x;
                downY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = x - downX;
                float moveY = y - downY;
                //通过此方法使View位置发生偏移，达到margin的作用却又不改变View的getLeft()的值。
                //恢复方法是setTranslationX(0)，而不是上一次偏移量的相反数。
                setTranslationX(moveX);
                setTranslationY(moveY);

                break;
            default:
                //复位
//                setTranslationX(getTop());
//                setTranslationY(getLeft());
                break;
        }
        return true;
    }
}
